#include "mytcpsocket.h"
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QHostAddress>
#include <QNetworkInterface>

// 获取本机 IP 地址
QString MyTcpSocket::getLocalIPAddress()
{

    QString ip_address;
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    for (int i = 0; i < ipAddressesList.size(); ++i)
    {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&  ipAddressesList.at(i).toIPv4Address())
        {
            ip_address = ipAddressesList.at(i).toString();
        }
    }
    if (ip_address.isEmpty())
        ip_address = QHostAddress(QHostAddress::LocalHost).toString();
    return ip_address;

}

MyTcpSocket::MyTcpSocket(QObject *parent)
    : QObject{parent}
{
    socket = new QTcpSocket;// 创建socket对象
    ServerIP = "192.168.10.6";
    PORT = 6666;
    socket->connectToHost(ServerIP, PORT);
    if(socket->waitForConnected(3000))
    {
        qDebug()<<"连接成功";
    }else{
        qDebug()<<"连接失败";
    }

    MyTcpSocket::HostIP = getLocalIPAddress();

    //通过信号接收服务器数据
    connect(socket, &QTcpSocket::readyRead,this, &MyTcpSocket::slotReadyRead);
}

MyTcpSocket::~MyTcpSocket()
{
    if(socket->isOpen())
    {
        socket->close();
    }
    delete socket;
}

bool MyTcpSocket::sendMsg(const QJsonObject &qmlJsonObject)
{
    if(socket->state() != QAbstractSocket::ConnectedState)
    {
        socket->disconnected();
        socket->connectToHost(ServerIP, PORT);
        if(socket->waitForConnected(3000))
        {
            qDebug()<<"连接成功";
        }else{
            qDebug()<<"连接失败";
        }
    }
    // JSON数据
    QJsonObject data, json;

    // 迭代qmlJsonObject中的属性并添加到value
    for (auto it = qmlJsonObject.begin(); it != qmlJsonObject.end(); ++it) {
        data[it.key()] = it.value();
    }

    json["ip"] = HostIP;
    json["data"] = data;

    // 构造JSON文档
    QJsonDocument jsonDoc(json);
    QByteArray jsonDataBytes = jsonDoc.toJson();
    socket->write(jsonDataBytes);
    //    socket->flush();
    if (socket->waitForBytesWritten(-1)) {
        qDebug() << "JSON data sent successfully.";
        return true;
    } else {
        qDebug() << "Failed to send JSON data."<<socket->errorString();
        return false;
    }
}

bool MyTcpSocket::updateDataFromSocket()
{
    return true;
}


void MyTcpSocket::slotReadyRead()
{
    QByteArray array = socket->readAll();

    if (!array.isEmpty())
    {
        QString recvMsg = QString::fromUtf8(array);
        recvMsg.replace(" ", ""); // Remove spaces

        // Define the regular expression pattern to match sensor data
        QRegularExpression rx("\\((.*?)\\)");

        // Create a QVariantList to hold the parsed data
        QVariantList newData;

        // Process each sensor data block and extract key-value pairs
        QRegularExpressionMatchIterator matchIterator = rx.globalMatch(recvMsg);
        while (matchIterator.hasNext())
        {
            QRegularExpressionMatch match = matchIterator.next();
            QStringList sensorDataList = match.captured(1).split('\n');
            QVariantMap sensorDataMap;

            foreach (const QString &sensorData, sensorDataList)
            {
                QStringList keyValue = sensorData.split(':');
                if (keyValue.size() == 2)
                {
                    QString key = keyValue[0].trimmed();
                    QString value = keyValue[1].trimmed();

                    sensorDataMap[key] = value;
                }
            }

            newData.append(sensorDataMap);
        }

        // Update the dataFromSocket property
        m_dataFromSocket = newData;
        qDebug()<<m_dataFromSocket;

        emit dataFromSocketChanged();
    }
}
